﻿/*
 * SUBJECT：基本操作控制器
 *          封装每个表的基本操作，包括6个常规方法
 *          1、查所有数据
 *          2、查所有数据带分页
 *          3、根据ID查一条数据
 *          4、添加数据
 *          5、删除数据
 *          6、修改数据
 * DATE：2023/2/8
 * **/
using Max.PH6_2006A.LowCode.DTO;
using Max.PH6_2006A.LowCode.IService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Max.PH6_2006A.LowCode.API.Controllers
{
    /// <summary>
    /// 基本的单表增删改查
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    //[Authorize]
    public class BaseCRUDController<T, TInput, TOuput> : ControllerBase where T : class,new()
    {
        IBaseService<T,TInput,TOuput> _service;

        public BaseCRUDController(IBaseService<T, TInput, TOuput> service)
        {
            _service = service;
        }

        /*
         * 6个接口
         * **/
        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        [HttpGet("query/all")]
        public async Task<IActionResult> QueryAsync()
        {
            DTO.ApiResultReturnDto dto = new();

            //2、调用业务
            string sql = GetSelectSqlByEntity<T>();
            var data = await _service.QueryAsync(sql);
            dto.Data = data;

            //3、统一返回值
            return Ok(dto);
        }


        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("query/pages")]
        public async Task<IActionResult> QueryAsync(int pageIndex, int pageSize)
        {
            DTO.ApiResultReturnDto dto = new();

            //1、参数判断
            if (pageIndex <= 0) pageIndex = 1;
            if(pageSize <= 0) pageSize = 10;

            //2、调用业务            
            string sql = GetSelectSqlByEntity<T>();
            var list = await _service.QueryAsync(sql);  //获取符合条件的数据

            int total = list.Count(); //所有符合条件的记录数

            //然后分页
            var data = list.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            dto.Data = new{ items = data,total };


            //3、统一返回值
            return Ok(dto);
        }

        /// <summary>
        /// 查询具体一条信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("first")]
        public async Task<IActionResult> QueryFirstAsync(string id)
        {
            DTO.ApiResultReturnDto dto = new();

            if (string.IsNullOrEmpty(id))
            {
                dto.Code = ApiResultReturnCode.Failed;
                dto.Message = "无效参数";
                return Ok(dto);
            }
            string sql = GetSelectSqlByEntity<T>();
             sql = $"{sql} where id=@id";
            Dapper.DynamicParameters param = new Dapper.DynamicParameters();
            param.Add("id", id);
            var data = await _service.QueryFirstAsync(sql, param);
            dto.Data = data;

            return Ok(dto);
        }

        ///// <summary>
        ///// 删除数据
        ///// </summary>
        ///// <param name="ids"></param>
        ///// <returns></returns>
        //[HttpDelete("delete")]
        //public async Task<IActionResult> DeleteAsync(List<string> ids)
        //{
        //    DTO.ApiResultReturnDto dto = new();

        //    if (ids == null || ids.Count <= 0)
        //    {
        //        dto.Code = ApiResultReturnCode.Failed;
        //        dto.Message = "无效参数";
        //        return Ok(dto);
        //    }

        //    int result = await _service.DeleteAsync(ids, typeof(T).Name);
        //    dto.Data = result;

        //    return Ok(dto);
        //}

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpDelete("delete")]
        public async Task<IActionResult> DeleteAsync(List<T> list)
        {
            DTO.ApiResultReturnDto dto = new();

            if (list == null || list.Count <= 0)
            {
                dto.Code = ApiResultReturnCode.Failed;
                dto.Message = "无效参数";
                return Ok(dto);
            }

            int result = await _service.DeleteAsync(list);
            dto.Data = result;

            return Ok(dto);
        }


        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPut("update")]
        public async Task<IActionResult> UpdateAsync(T user)
        {
            DTO.ApiResultReturnDto dto = new();

            int result = await _service.UpdateAsync(user);
            dto.Data = result;

            return Ok(dto);
        }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost("insert")]
        public async Task<IActionResult> InsertAsync(TInput user)
        {
            DTO.ApiResultReturnDto dto = new();

            int result = await _service.InsertAsync(user, typeof(T).Name);
            dto.Data = result;

            return Ok(dto);
        }


        private string GetSelectSqlByEntity<T>()
        {
            var t = typeof(T);
            var tableName = t.Name;
            string sql = $"select * from {tableName}";
            return sql;
        }
    }
}
